package com.example.rabcdemo.controller;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.rabcdemo.annotation.RequestPermission;
import com.example.rabcdemo.entity.*;
import com.example.rabcdemo.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("login")
    public void login(){
        //1.登录（模拟）
        User user = userService.getById("1001");
        //2.通过用户id找到角色id userId->roleId->role
        LambdaQueryWrapper<UserRole> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getUserId());
        UserRole userRole = userRoleService.getOne(wrapper);
        String roleId = userRole.getRoleId();
        Role role = roleService.getById(roleId);
        //3.角色id找到对应的所拥有权限
        LambdaQueryWrapper<RolePermission> wrapper2=new LambdaQueryWrapper<>();
        wrapper2.eq(RolePermission::getRoleId,roleId);
        List<RolePermission> list = rolePermissionService.list(wrapper2);

        //收集从数据库中读出来的对应角色的权限 -> 只存表达式
        List<String> permissions=new ArrayList<>();
        for (RolePermission rolePermission : list) {
            //最终权限id
            String permissionId = rolePermission.getPermissionId();
            Permission permission = permissionService.getById(permissionId);
            log.info("{}",permission);
            permissions.add(permission.getExpression());
        }
        //4.签发token，并且把权限存入到redis中
        String token = JWT.create()
                .setPayload("id", user.getUserId())
                .setPayload("roleId", roleId)
                .setPayload("time", System.currentTimeMillis())
                .setKey("1234".getBytes())
                .sign();
        //5.把数据存入到redis，token作为key，权限列表作为value
        redisTemplate.opsForList().rightPushAll(token,permissions);
        log.info("token:{}",token);
    }

}
